<template>
    <div class="live-room-wrapper">
      <!-- 顶部操作栏 -->
      <div class="top-bar">
        <el-button size="small" type="danger" @click="leaveChannel" :disabled="!joined">离开直播间</el-button>
        <el-button size="small" @click="toggleToolbox">{{ toolboxCollapsed ? '展开工具栏' : '收起工具栏' }}</el-button>
        <el-button size="small" @click="toggleChat">{{ showChat ? '关闭聊天' : '打开聊天' }}</el-button>
      </div>
  
      <!-- 主视频区域 -->
      <div class="video-area">
        <div id="video-container" class="video-box"></div>
      </div>
  
      <!-- 工具栏 -->
      <transition name="fade">
        <div v-if="!toolboxCollapsed && isHost" class="toolbox">
          <el-button size="small" @click="startScreenShare">屏幕共享</el-button>
          <el-button size="small" @click="toggleRecording">{{ isRecording ? '停止录制' : '开始录制' }}</el-button>
          <el-button size="small" @click="openVoteDialog">发起投票</el-button>
        </div>
      </transition>
  
      <!-- 聊天框 -->
      <transition name="slide-fade">
        <div v-if="showChat" class="chat-box">
          <div class="chat-header">实时消息</div>
          <div class="chat-content">
            <div class="chat-messages" ref="chatContainer">
              <div v-for="msg in messageList" :key="msg.id" class="chat-message">
                <strong>{{ msg.userName || msg.uid }}：</strong>{{ msg.text }}
              </div>
            </div>
            <div class="chat-input">
              <el-input
                v-model="messageText"
                placeholder="输入消息"
                @keyup.enter="sendMessage"
                size="small"
              />
              <el-button size="small" type="primary" @click="sendMessage">发送</el-button>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </template>
  
  
  
  <script setup>
  import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
  import { useRoute } from 'vue-router'
  import DingRTC from 'dingrtc'
  import RTM from '@dingrtc/rtm'
  import { ElMessage } from 'element-plus'
  
  // 获取 URL 参数
  const route = useRoute()
  const uid = route.query.uid
  const token = route.query.token
  const userName = route.query.userName
  const hostId = route.query.hostId
  
  if (!uid || !token || !hostId) {
    ElMessage.error('直播间参数缺失')
    throw new Error('Missing required query parameters')
  }
  
  // ✅ 当前用户是否是主播
  const isHost = computed(() => uid === hostId)
  
  const joined = ref(false)
  const isRecording = ref(false)
  const toolboxCollapsed = ref(false)
  const messageText = ref('')
  const messageList = ref([])
  const showChat = ref(true)
  let messageCounter = 0
  let client = null
  let cameraTrack = null
  let micTrack = null
  let screenTrack = null
  let mediaRecorder = null
  let recordedChunks = []
  
  const sessionId = 'lesson-session'
  const rtm = new RTM()
  
  // 聊天容器 DOM 引用（用于自动滚动）
  const chatContainer = ref(null)
  
  watch(messageList, () => {
    nextTick(() => {
      const el = chatContainer.value
      if (el) el.scrollTop = el.scrollHeight
    })
  })
  
  function appendTrackToContainer(track) {
    const el = document.getElementById('video-container')
    if (el) {
      el.innerHTML = ''
      track.play(el)
    }
  }
  
  async function joinChannel() {
    try {
      client = DingRTC.createClient()
      client.register(rtm)
  
      // 聊天消息监听
      rtm.on('message', (data) => {
        const decoder = new TextDecoder()
        const msgString = decoder.decode(data.message)
        try {
          const parsed = JSON.parse(msgString)
          messageList.value.push({ id: messageCounter++, ...parsed })
        } catch {
          messageList.value.push({ id: messageCounter++, uid: data.uid, userName: data.uid, text: msgString })
        }
      })
  
      await client.join({ appId: 'owz8psw2', token, uid, channel: 'channel1', userName })
      await rtm.joinSession(sessionId)
  
      if (isHost.value) {
        cameraTrack = await DingRTC.createCameraVideoTrack({ frameRate: 15, dimension: 'VD_1280x720' })
        micTrack = await DingRTC.createMicrophoneAudioTrack()
        appendTrackToContainer(cameraTrack)
        await client.publish([cameraTrack, micTrack])
      } else {
        // ✅ 访客订阅主播的视频/音频
        const videoTrack = await client.subscribe(hostId, 'video')
        appendTrackToContainer(videoTrack)
        const audioTrack = await client.subscribe('mcu', 'audio')
        audioTrack.play()
      }
  
      // ✅ 监听主播屏幕共享（访客接收）
      client.on('user-published', async (userId, mediaType) => {
        if (mediaType === 'video' && userId === hostId) {
          const track = await client.subscribe(userId, 'video')
          appendTrackToContainer(track)
        }
      })
  
      client.on('user-unpublished', () => {
        const el = document.getElementById('video-container')
        if (el) el.innerHTML = ''
      })
  
      joined.value = true
    } catch (error) {
      console.error('加入失败:', error)
    }
  }
  
  async function leaveChannel() {
    if (!joined.value) return
    try {
      await rtm.leaveSession(sessionId)
      await client.unpublish([cameraTrack, micTrack, screenTrack].filter(Boolean))
      ;[cameraTrack, micTrack, screenTrack].forEach(track => track?.stop?.() && track?.close?.())
      await client.leave()
      joined.value = false
      document.getElementById('video-container').innerHTML = ''
    } catch (error) {
      console.error('离开失败:', error)
    }
  }
  
  async function startScreenShare() {
    try {
      [screenTrack] = await DingRTC.createScreenVideoTrack({ frameRate: 15, dimension: 'VD_1280x720' })
      await client.publish(screenTrack)
      appendTrackToContainer(screenTrack)
    } catch (error) {
      console.error('屏幕共享失败:', error)
    }
  }
  
  function toggleRecording() {
    const stream = document.querySelector('video')?.captureStream?.()
    if (!stream) return alert('无法获取视频流')
    if (!isRecording.value) {
      recordedChunks = []
      mediaRecorder = new MediaRecorder(stream, { mimeType: 'video/webm' })
      mediaRecorder.ondataavailable = e => { if (e.data.size > 0) recordedChunks.push(e.data) }
      mediaRecorder.onstop = () => {
        const blob = new Blob(recordedChunks, { type: 'video/webm' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `lesson-${Date.now()}.webm`
        a.click()
      }
      mediaRecorder.start()
      isRecording.value = true
    } else {
      mediaRecorder.stop()
      isRecording.value = false
    }
  }
  
  function sendMessage() {
    if (!messageText.value) return
    const encoder = new TextEncoder()
    const message = JSON.stringify({ uid, userName, text: messageText.value })
    rtm.publish(sessionId, encoder.encode(message))
    messageList.value.push({ id: messageCounter++, uid, userName, text: messageText.value }) // 本地显示
    messageText.value = ''
  }
  
  // 🔽 投票弹窗控制
  const voteDialogVisible = ref(false)
  const voteQuestion = ref('')
  
  function openVoteDialog() {
    voteDialogVisible.value = true
  }
  
  function sendVote() {
    if (!voteQuestion.value.trim()) {
      ElMessage.warning('请输入投票问题')
      return
    }
    const encoder = new TextEncoder()
    const message = JSON.stringify({ uid, userName, text: `【投票】${voteQuestion.value}` })
    rtm.publish(sessionId, encoder.encode(message))
    messageList.value.push({ id: messageCounter++, uid, userName, text: `【投票】${voteQuestion.value}` })
    voteDialogVisible.value = false
    voteQuestion.value = ''
  }
  function toggleChat() {
    showChat.value = !showChat.value
  }
  
  function toggleToolbox() {
    toolboxCollapsed.value = !toolboxCollapsed.value
  }
  
  onMounted(joinChannel)
  onBeforeUnmount(leaveChannel)
  
  </script>
  
  
  <style scoped>
  .live-room-wrapper {
    width: 100%;
    height: 100vh;
    background-color: #f0f2f5;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  /* 视频区域缩小一点 */
  .video-area {
    width: 65vw;
    max-width: 800px;
    aspect-ratio: 16 / 9;
    background-color: #000;
    border-radius: 8px;
    box-shadow: 0 0 12px rgba(0, 0, 0, 0.2);
    overflow: hidden;
    position: relative;
  }
  
  .video-box {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  
  /* 顶部操作栏 */
  .top-bar {
    position: absolute;
    top: 8px;
    left: 12px;
    display: flex;
    gap: 8px;
    z-index: 10;
  }
  
  /* 底部工具栏 */
  .toolbox {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 8px;
    z-index: 10;
  }
  
  /* 聊天框优化：更紧凑 */
  .chat-box {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 280px;
    height: 420px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    padding: 8px;
    display: flex;
    flex-direction: column;
    font-size: 13px;
    z-index: 20;
  }
  
  .chat-header {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 6px;
  }
  
  .chat-content {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    font-size: 13px;
    margin-bottom: 6px;
    padding-right: 4px;
  }
  
  .chat-message {
    margin-bottom: 5px;
    line-height: 1.4;
  }
  
  .chat-input {
    display: flex;
    gap: 4px;
  }
  
  /* 动画过渡 */
  .fade-enter-active, .fade-leave-active,
  .slide-fade-enter-active, .slide-fade-leave-active {
    transition: all 0.25s ease;
  }
  .slide-fade-enter-from, .slide-fade-leave-to {
    opacity: 0;
    transform: translateX(100%);
  }
  
  </style>
  